const express = require('express');
const router = express.Router();
const db = require('../../../../util/dbConfig/dbConfig')
const dateReplace = require('../../../../public/javascripts/timeFormat')

router.post('/single', async (req,res) => {
    //鉴权
    if(req.session.userInfo.admin === 1 || !req.session.userInfo) {
        return res.send({
            code: 3,
            msg: '您未登录或权限不够'
        })
    }
    // let obj = {
    //     ID:4,         //索引为该条信息的id
    //     //以上为修改索引
    //     brDate:'2021-12-15T13:15:001Z',     //配种时间
    //     cgDate:'2021-12-15T13:15:001Z',     //产羔时间
    //     sex:null,        //性别
    // }
    let {
        ID,         //索引为该条信息的id
        //以上为修改索引
        brDate,     //配种时间
        cgDate,     //产羔时间
        sex,        //性别
    }=req.body
  console.log(req.body)
    if(brDate !== undefined){
        brDate = await dateReplace(brDate,res)
    }
    if(cgDate !== undefined ){
        cgDate =  await dateReplace(cgDate,res)
    }

  if (sex === '公') {
      sex = '1'
  } else if (sex === '母') {
    sex = '2'
  } 

    let dataArr = [
        brDate,     //配种时间
        cgDate,     //产羔时间
        sex,        //性别
    ]
    let decArr = [
        'br_date',
        'cg_date',
        'sex',
    ]
    let dataArrA = []
    let decArrA = []
    for(let i = 0; i<dataArr.length; i++){
        if(dataArr[i]){
             dataArrA.push(dataArr[i])
             decArrA.push(decArr[i])
        }

    }
    try{
        let sql = `update hybridization set`
        //拼接sql语句
        for(let j = 0; j< dataArrA.length; j++){
            if(dataArrA[j]){
                sql = sql + ' ' + `${decArrA[j]}='${dataArrA[j]}' `
            }
            if(j !== dataArrA.length -1){
                sql = sql + ','
            }
        }
        sql = sql + ' ' + `where ID=${ID}`
        let result = await db.SySqlConnect(sql,[])
        if(result.affectedRows !== 0 ){
            return res.send({
                code: 0,
                msg: '添加成功'
            })
        }else {
            return res.send({
                code: 2,
                msg: '添加失败'
            })
        }
    }catch (e) {
        console.log(e);
        return res.send({
            code: 4,
            msg: '服务器错误，请稍后再试'
        })
    }
})

module.exports = router
